from db.sql import engine
from db.sql import Texture
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.sql.expression import func, select
import os
import numpy as np
import cv2

DBSession = sessionmaker(bind=engine)
session = DBSession()


def insert(object):
    '''
    Insert a image
    :param object:
    :return: bool
    '''
    try:
        session.add(object)
        session.commit()
        return True
    except InvalidRequestError:
        session.rollback()
    except Exception as e:
        print(e)
        return False


def query_random():
    return session.query(Texture).order_by(func.random()).first()


def compute(path):
    # file_names = os.listdir(path)
    per_image_Rmean = []
    per_image_Gmean = []
    per_image_Bmean = []
    # for file_name in file_names:
    img = cv2.imread(path)
    # per_image_Bmean.append(np.mean(img[:,:,0]))
    # per_image_Gmean.append(np.mean(img[:,:,1]))
    # per_image_Rmean.append(np.mean(img[:,:,2]))
    R_mean = np.mean(img[:, :, 0])
    G_mean = np.mean(img[:, :, 1])
    B_mean = np.mean(img[:, :, 2])
    return R_mean, G_mean, B_mean


if __name__ == '__main__':
    # print(query_random().to_json())
    # run the code to add texture in sqlite
    # 注意mac下路径 '/' 分割 win下路径 '\'分割
    dir = r"../src/filler"
    folders = ['punctate', 'linear', 'planar', 'lumpy', 'varicolored']
    for f in folders:
        for i in os.listdir(os.path.join(dir, f)):
            (filename, extension) = os.path.splitext(i)  # 将文件名拆分为文件名与后缀
            if extension in ['.jpg', '.bmp', '.png']:
                # file = open(os.path.join(dir, f, filename + '.txt'), 'r')
                # line = file.readline()
                # print(line)
                R, G, B = compute(os.path.join(dir, f, i))
                # print(R, G, B)
                insert(Texture(path=os.path.join(r"src/filler", f, i), R=R, G=G, B=B, type=f))
